package cn.opencodes.framework.autoconfigure;

import org.apache.shiro.authz.AuthorizationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.TypeMismatchException;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import cn.opencodes.framework.tools.vo.RException;
import cn.opencodes.framework.tools.vo.CoreConst;
import cn.opencodes.framework.tools.vo.R;

/**
 * 异常处理器
 * @author HJ
 */
@RestControllerAdvice
public class RExceptionConfiguration {
	private Logger logger = LoggerFactory.getLogger(getClass());
	
	//400错误-参数类型错误
    @ExceptionHandler({TypeMismatchException.class})
    public R requestTypeMismatch(TypeMismatchException e) {
    	logger.error(e.getMessage(), e);
		return R.error(CoreConst.HttpStatus.PARAM_ERROR.value(), "参数类型错误");
    }

    //
    //400错误-缺失参数
    @ExceptionHandler({MissingServletRequestParameterException.class})
    public R requestMissingServletRequest(MissingServletRequestParameterException e) {
        logger.error(e.getMessage(), e);
		return R.error(CoreConst.HttpStatus.PARAM_ERROR.value(), "缺失参数错误");
    }

	/**
	 * 处理自定义异常
	 */
	@ExceptionHandler(RException.class)
	public R handleRRException(RException e){
		return R.error(e.getCode(), e.getMessage());
	}

	@ExceptionHandler(DuplicateKeyException.class)
	public R handleDuplicateKeyException(DuplicateKeyException e){
		logger.error(e.getMessage(), e);
		return R.error(CoreConst.HttpStatus.EXISTS.value(), "数据库中已存在该记录");
	}

	@ExceptionHandler(AuthorizationException.class)
	public R handleAuthorizationException(AuthorizationException e){
		logger.error(e.getMessage(), e);
		return R.error(CoreConst.HttpStatus.UNAUTHORIZED.value(), "没有权限，请联系管理员授权");
	}

	@ExceptionHandler(Exception.class)
	public R handleException(Exception e){
		logger.error(e.getMessage(), e);
		return R.error(e.getMessage());
	}
}
